const WebSocket = require('ws');
const ClassicGameMode = require('../Game/ClassicGameMode');
const jwt = require('jsonwebtoken');
const db = require('../database/db');
const wss = new WebSocket.Server({ port: 9090 });

let currentGameMode = null;

// 验证token的函数
function verifyToken(token, ws) {
    jwt.verify(token, process.env.SECRETKEY, (err, decoded) => {
        if (err) {
            ws.send(JSON.stringify({ type: "token_verify", status: "fail" }));
        } else {
            ws.send(JSON.stringify({ type: "token_verify", status: "success" }));
        }
    });
}

// 处理消除卡牌消息的函数
async function handleCardElimination(data, ws) {
    try {
        const token = data.token;
        const decoded = await new Promise((resolve, reject) => {
            jwt.verify(token, process.env.SECRETKEY, (err, decoded) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(decoded);
                }
            });
        });

        const userId = decoded.user_id;
        // 查询当前金币数量
        const sqlGetCoins = 'SELECT coins FROM userdata WHERE user_id = ?';
        const resultGetCoins = await new Promise((resolve, reject) => {
            db.query(sqlGetCoins, [userId], (err, result) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });

        if (resultGetCoins.length > 0) {
            const currentCoins = resultGetCoins[0].coins;
            const newCoins = currentCoins + 1; // 每次消除卡牌增加1金币，可根据需求调整

            // 更新金币数量
            const sqlUpdateCoins = 'UPDATE userdata SET coins = ? WHERE user_id = ?';
            await new Promise((resolve, reject) => {
                db.query(sqlUpdateCoins, [newCoins, userId], (err, result) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(result);
                    }
                });
            });

            ws.send(JSON.stringify({ type: "coins_updated", newCoins }));
        }
    } catch (error) {
        console.error(error);
        ws.send(JSON.stringify({ type: "error", message: "Database error" }));
    }
}

wss.on('connection', function connection(ws) {
    console.log('New Connection');

    ws.on('message', function incoming(message) {
        try {
            const data = JSON.parse(message);
            switch (data.type) {
                case "token_verify":
                    // 验证token
                    verifyToken(data.token, ws);
                    break;
                case "ClassicGame":
                    // 使用单例模式获取实例
                    currentGameMode = ClassicGameMode.getInstance(ws);
                    // 只在第一次调用时初始化
                    if (!currentGameMode.initialized) {
                        currentGameMode.init();
                    }
                    break;
                case "card_elimination":
                    // 处理消除卡牌消息
                    handleCardElimination(data, ws);
                    break;
                default:
                    ws.send(JSON.stringify({ msg: "游戏模式选择出错" }));
                    break;
            }
        } catch (error) {
            console.error(error);
            ws.send(JSON.stringify({ msg: "消息解析错误" }));
        }
    });

    ws.on('close', function close() {
        console.log('disconnected');
    });
});

console.log('WebSocket server listening on port 9090');

// 关闭 WebSocket 服务器的函数
function close() {
    wss.close(() => {
        console.log('WebSocket server closed');
    });
}

module.exports = {
    close
};
